import { createRouter, createWebHistory } from 'vue-router'
import { routes } from './routes'
import { ACCESS_ENUM } from '@/access/accessEnum'
import checkAccess from '@/access/checkAccess'
import { useLocalStorage } from '@vueuse/core'
import NProgress from '@/plugins/nprogress'
const AccessToken = useLocalStorage('access_token', null)
const RefreshToken = useLocalStorage('refresh_token', null)
const router = createRouter({
    history: createWebHistory(),
    routes
})
router.beforeEach(async (to, from, next) => {
    NProgress.start()
    if (to.matched.length === 0 && to.path !== '/notfound') {
        next({name : 'notfound'})
        return
    }
    if (to.fullPath.startsWith('/user/login') || to.fullPath == '/user/register') {
        next()
        return
    }
    if (AccessToken.value == null) {
        if (to.fullPath == '/') next({name: 'login'})
        else next({ name: 'login', query: { redirect: to.fullPath } })
        return
    }
    const LoginUserRole = ACCESS_ENUM.USER
    const needAccess = (to?.meta.access as number) ?? ACCESS_ENUM.USER
    // if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {
    //     if (LoginUserRole === ACCESS_ENUM.NOT_LOGIN) {
    //         next(`/user/login?redirect=${to.fullPath}`)
    //         return
    //     }
    // }
    if (!checkAccess(LoginUserRole, needAccess)) {
        next({name: 'notauth'})
        return
    }
    next()
})
router.afterEach((to, from) => {
    NProgress.done()
    window.scrollTo(0, 0)
})
export default router
